package com.ruoyi.StarStudio.Utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


public class QrCodeUtils {

    private static final String appid = "wxa7a8a20b86c87eb7";
    private static final String appsecret = "6426a1f2acddf95268a835f125e61589";

    // 网页授权接口
    public static String GetAccessTokenUrl =
            "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";

    //获取AccessToken
    public static String getAccessToken() {
        String requestUrl = GetAccessTokenUrl.replace("APPID", appid).replace("SECRET", appsecret);
        String accessToken = null;
        String result = null;

        // 获取当前客户端对
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet request = new HttpGet(requestUrl);
            // 通过请求对象获取响应对象
            HttpResponse response = httpclient.execute(request);
            // 判断请求结果状态码
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity());
                JSONObject object = JSONObject.parseObject(result);
                accessToken = object.get("access_token").toString();
            }
            //释放连接
            httpclient.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    //获取小程序码
    public static ResponseEntity<byte[]> getQrCode(String sceneStr, String accessToken, String filepath, String page) {
        RestTemplate rest = new RestTemplate();
        InputStream inputStream = null;
        OutputStream outputStream = null;

        //生成小程序码并存储在本地
        try {
            String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+accessToken;
            //请求体参数
            Map<String,Object> param = new HashMap<>();
            param.put("scene", sceneStr);
            param.put("page", page);  //不加参数时默认为主页面，加上参数后跳转到指定页面
            param.put("width", 430);
            param.put("auto_color", false);
            Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
//            System.out.println("调用生成微信URL接口传参:" + param);

            LinkedMultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
//            System.out.println("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
//            System.out.println(Base64.encodeBase64String(result));

            //小程序码写入文件
            inputStream = new ByteArrayInputStream(result);
            File file = new File(filepath);
            if (!file.exists()){
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);

            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();

        } catch (Exception e) {
            System.out.println("调用小程序生成微信永久小程序码URL接口异常");
            e.printStackTrace();
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //返回小程序码
//        InputStream imgin = null;
//        try {
//            imgin = new FileInputStream(filepath);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//        try {
//            return IOUtils.toByteArray(imgin);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;

        //返回小程序码的可下载文件
        try {
            File file = new File(filepath);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentDispositionFormData("attachment",
                    new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            headers.add("Access-Control-Expose-Headers", "Content-Disposition");
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

            // 获取文件的字节数组
            byte[] content = FileUtils.readFileToByteArray(file);
            return new ResponseEntity<>(content, headers, org.springframework.http.HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
